package net.da.core.bof.spi.local;

import java.util.Calendar;

import net.da.core.bof.ApplicationSession;
import net.da.core.bof.OrganizationUser;
import net.da.core.bof.SysUser;
import net.da.core.bof.User;
import net.da.core.entity.ApplicationSessionEntity;
import net.da.core.exception.DaException;

public class ApplicationSessionImpl<E extends ApplicationSessionEntity> extends
        PersistentObjectImpl<ApplicationSessionEntity> implements ApplicationSession {

    public ApplicationSessionImpl() {
        super();
    }

    public ApplicationSessionImpl(ApplicationSessionEntity entity) {
        super(entity);
    }

    public ApplicationSessionEntity getEntity() {
        return (ApplicationSessionEntity) super.getEntity();
    }

    public Class getEntityClass() {
        return ApplicationSessionEntity.class;
    }

    /*
     * What is the difference between disconnect and shutdown?
     *
     */
    public void disconnect() throws DaException {
        throw new UnsupportedOperationException();
    }

    public void shutdown() throws DaException {
        throw new UnsupportedOperationException();
    }

    // TODO: this method should be refactored to hide password
    public User getUser() {
        if (getEntity().getSysUser() != null) {
            return businessObjectManager.getBusinessObjectByEntity(SysUser.class, getEntity().getSysUser());
        } else if (getEntity().getOrganisationUser() != null) {
            return businessObjectManager.getBusinessObjectByEntity(OrganizationUser.class, getEntity().getOrganisationUser());
        } else {
            return null;
        }
    }

    public boolean isConnected() {
        throw new UnsupportedOperationException();
    }

    public Calendar getExpirationTime() {
        return getEntity().getExpirationTime();
    }

    public Calendar getLastTime() {
        return getEntity().getLastTime();
    }

    public void setExpirationTime(Calendar expirationTime) {
        getEntity().setExpirationTime(expirationTime);
    }

    public void setLastTime(Calendar lastTime) {
        getEntity().setLastTime(lastTime);
    }

    public void setAuthorizationCode(String sessionId) {
        getEntity().setSessionId(sessionId);
    }

    public String getAuthorizationCode() {
        return getEntity().getSessionId();
    }

    public void setUser(User user) {
        if (user instanceof SysUser) {
            getEntity().setSysUser(((SysUserImpl) user).getEntity());
        } else if (user instanceof OrganizationUser) {
            getEntity().setOrganisationUser(((OrganizationUserImpl) user).getEntity());
        } else {
            throw new IllegalArgumentException("Wrong user!");
        }
    }

    @Override
    protected void preSaveValidation() throws DaException {
    }

}
